package com.easylinkin.linkappapi.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * class info :监听Spring Session会话创建、销毁
 *
 * @author liuqihang
 * @date 2021/8/18 16:51
 */
@Component
@Slf4j
public class MySessionListener implements HttpSessionListener {

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        String sessionId = session.getId();
        log.info("(listener)session destroyed sessionId=" + sessionId);
        log.info("(listener)session:" + sessionId + "==> destroyed maxInactiveInterval=" + session.getMaxInactiveInterval());
        log.info("(listener)session:" + sessionId + "==> destroyed creationTime=" + session.getCreationTime());
        log.info("(listener)session:" + sessionId + "==> destroyed lastAccessedTime=" + session.getLastAccessedTime());

        SecurityContext securityContext = parseSessionAttribute(session);
        if(securityContext != null){
            Authentication authentication = securityContext.getAuthentication();
            if(authentication != null){
                String userName = authentication.getName();
                log.info("(listener)session:" + sessionId + "==> destroyed userName=" + userName);
            }
        }
    }

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        String sessionId = session.getId();
        log.info("(listener)session create id=" + session.getId());
        log.info("(listener)session:" + sessionId + "==> create maxInactiveInterval=" + session.getMaxInactiveInterval());
        log.info("(listener)session:" + sessionId + "==> create creationTime=" + session.getCreationTime());
        log.info("(listener)session:" + sessionId + "==> create lastAccessedTime=" + session.getLastAccessedTime());
        SecurityContext securityContext = parseSessionAttribute(session);
        if(securityContext != null){
            Authentication authentication = securityContext.getAuthentication();
            if(authentication != null){
                String userName = authentication.getName();
                log.info("(listener)session:" + sessionId + "==> create userName=" + userName);
            }
        }
    }

    private SecurityContext parseSessionAttribute(HttpSession session){
        SecurityContextImpl securityContext = (SecurityContextImpl)session.getAttribute("SPRING_SECURITY_CONTEXT");
        return securityContext;
    }

}
